#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
  int fpin, fpout;
  off_t res;
  off_t filesize;
  int interpolation_val;
  int decimation_val;
  char current_byte = 0;
  int i,j,pos;

  if(argc < 4)
  {
    printf("please use %s interpolation_val decimation_val inputfile.gray outputfile.gray\n", argv[0]);
    return 1;
  }
  interpolation_val  = atoi(argv[1]);
  decimation_val  = atoi(argv[2]);

  fpin = open(argv[3], O_RDONLY);
  if(fpin < 0)
  {
    printf("input file %s could not be opened\n", argv[3]);
    return 2;
  }
  fpout = open(argv[4], O_CREAT|O_RDWR|O_TRUNC,S_IRUSR|S_IWUSR);
  if(fpout < 0)
  {
    printf("output file %s could not be opened\n", argv[4]);
    return 2;
  }
  filesize = lseek(fpin, 0L, SEEK_END);
  if(filesize < 0)
  {
    perror("fseek1");
    return 3;
  }
  res = lseek(fpin, (off_t)0, SEEK_SET);
  if(res < 0)
  {
    perror("fseek2");
    return 4;
  }

  printf("inputfile has %0ld bytes, interpolation_val %0d decimation_val %0d\n", filesize, interpolation_val, decimation_val);
  pos=0;
  for(i=0;i<filesize;i++)
  {
    if(read(fpin, &current_byte, 1)<0)
    {
      perror("read");
      return 5;
    }
    for(j=0;j<interpolation_val;j++)
    {
      pos++;
      /////////////////////////////////////////////////////
      //
      // 1  2  3  4  5  6  7  8  9 10 11 12
      // 1  1  1  2  2  2  3  3  3  4  4  4
      // 1     1     2     3     3     4  
      //
      if(pos%decimation_val==0)
      {
        if(write(fpout, &current_byte, 1)<0)
        {
          perror("write");
          return 5;
        }
      }
    }
  }
  close(fpin);
  close(fpout);
  return 0;
}
